<template>
  <div class="main" ref="mainContainer">
    <div class="header" ref="headerContainer">
      <div class="header-actions">
        <el-upload
          style="display: flex; align-items: center; margin-right: 10px"
          :show-file-list="false"
          :with-credentials="true"
          :multiple="true"
          :http-request="addfile"
        >
          <el-button type="primary">
            <el-icon>
              <Promotion />
            </el-icon>
            <span>上传文件</span>
          </el-button>
        </el-upload>
        <el-button type="primary" @click="addfloder">新建文件夹</el-button>
        <el-button
          type="primary"
          @click="deletefile"
          :disabled="selectListfiles.length == 0"
          >批量删除</el-button
        >
        <el-button type="primary" @click="movefileBatch">批量移动</el-button>

        <div class="search-panle">
          <el-input placeholder="请输入搜索关键词" clearable> </el-input>
        </div>
        <div class="refresh" @click="refresh(currentFolder.fileId)">
          <el-icon><Refresh /></el-icon>
        </div>

        <!-- 导航 -->
      </div>
      <MyNavigation
        class="Mynavigation"
        ref="MyNavigationref"
        :dataList="datalistNavigation"
        @watchFolderFiles="watchFolderFiles"
      >
      </MyNavigation>
    </div>

    <div class="file-list">
      <MyTable
        ref="tableRef"
        :dataSource="tableData"
        :columns="columns"
        :filePid="currentFolder.fileId"
        :fetch="loadDataList"
        :initFetch="true"
        :options="tableOptions"
        @rowSelected="rowSelected"
        @rowdbselected="rowdbselected"
        @folder-click="loadFolderContent"
      >
        <template #fileName="{ index, row }">
          <div
            class="fileName"
            @mouseenter="showOp(row)"
            @mouseleave="cancelOp(row)"
          >
            <template
              v-if="
                (row.fileType === 1 || row.fileType === 3) && row.status == 2
              "
            >
              <icon :cover="row.fileCover" :width="32"></icon>
            </template>
            <template v-else>
              <icon
                v-if="row.folderType == 0"
                :width="32"
                :fileType="row.fileType"
              ></icon>
              <icon v-if="row.folderType == 1" :width="32" :fileType="0"></icon>
            </template>
            <span class="file-name" :title="row.fileName" v-if="!row.showEidt">
              <span
                style="cursor: pointer"
                :title="row.fileName"
                @click="gotoNewFolder(row)"
                >{{ row.fileName }}</span
              >
              <span v-if="row.status == 0">转码中</span>
              <span v-if="row.status == 1">转码失败</span>
            </span>

            <div class="edit-panle" v-if="row.showEidt">
              <el-input
                v-model.trim="row.fileNameReal"
                placeholder="请输入文件名"
                clearable
                :maxlength="190"
                @keyup.enter="SaveNameEdit(index)"
                ref="inputEditRef"
              >
                <template #suffix>{{ row.fileSuffix }} </template>
              </el-input>
              <el-button
                type="primary"
                style="margin-left: 10px"
                @click="SaveNameEdit(index)"
                >确认</el-button
              >
              <el-button @click="cancelEdit(index)">取消</el-button>
            </div>
            <div
              v-if="
                row.showOp && row.fileId && row.status == 2 && !row.showEidt
              "
              class="fileedits"
            >
              <span
                ><el-icon><Share /></el-icon>分享</span
              >
              <span
                ><el-icon><Download /></el-icon>下载</span
              >
              <span @click="delfile(row)"
                ><el-icon><Delete /></el-icon>删除</span
              >
              <span @click="reNamefoloderEdit(index)"
                ><el-icon><Edit /></el-icon>重命名</span
              >
              <span @click="MoveAsingleFile(row)"
                ><el-icon><Rank /></el-icon>移动</span
              >
            </div>
          </div>
        </template>
        <template #fileSize="{ row }">
          <div v-if="row.fileSize">{{ proxy.bit(row.fileSize) }}</div>
        </template>
      </MyTable>
    </div>

    <FolderSelect
      ref="folderSelectRef"
      @FolderSelectSubmitEvent="FolderSelectSubmitEvent"
    ></FolderSelect>
    <!-- <router-view></router-view> -->
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  getCurrentInstance,
  nextTick,
  onMounted,
  onUnmounted,
} from "vue";
const { proxy } = getCurrentInstance();
const folderSelectRef = ref();
const api = {
  loadDataList: "/file/loadDataList",
  rename: "/file/rename",
  newFolder: "/file/newFoloder",
  getFolderInfo: "/file/getFolderInfo",
  delFile: "/file/delFile",
  changeFileFolder: "/file/changeFileFolder",
  createDownLoadUrl: "/file/createDownloadUrl",
  download: "/api/file/download",
};
const tableRef = ref();
const tableData = ref({});
const columns = [
  {
    label: "文件名",
    prop: "fileName",
    scopedSlots: "fileName",
    align: "left",
  },
  {
    label: "文件大小",
    prop: "fileSize",
    width: 100,
    scopedSlots: "fileSize",
  },
  {
    label: "修改时间",
    prop: "lastUpdateTime",
    width: 200,
  },
];
const category = ref("all");
const fileNameFuzzy = ref();
const loadDataListByCategory = async (categorynum) => {
  category.value = categorynum;
  loadDataList(currentFolder.value.fileId);
};
const loadFolderContent = async (folder) => {};

const refresh = (filePid = 0) => {
  loadDataList(filePid);
};
const loadDataList = async (filePid = 0, pageNo) => {
  let params = {
    filePid,
    category: category.value,
    pageNo: tableData.value.pageNo || 1,
    pageSize: tableData.value.pageSize || 10,
    // fileNameFuzzy: fileNameFuzzy.value,
  };
  if (params.category !== "all") {
    delete params.filePid;
  }
  if (pageNo) {
    params.pageNo = pageNo;
  }
  let res = await proxy.request({
    url: api.loadDataList,
    params,
  });
  if (!res) {
    return;
  }
  tableData.value = res.data;
};
//查看文件夹内容
const watchFolderFiles = (items) => {
  if (currentFolder.value.fileId == items.fileId) {
    return;
  } else {
    const exists = datalistNavigation.value.some(
      (item) => item.fileId === items.fileId
    );
    if (!exists && items.fileId != 0) {
      datalistNavigation.value.push({
        fileName: items.fileName,
        fileId: items.fileId,
      });
    } else {
      if (items.fileId == 0) {
        datalistNavigation.value = [];
      }
      // 删除该 fileId 及其之后的所有项
      const index = datalistNavigation.value.findIndex(
        (item) => item.fileId === items.fileId
      );
      if (index !== -1) {
        datalistNavigation.value = datalistNavigation.value.slice(0, index + 1);
      }
    }
    currentFolder.value.fileId = items.fileId;
    loadDataList(items.fileId, 1);
  }
};
const tableOptions = ref({
  extHight: 50,
  selectType: "checkbox",
  showPagination: true,
});

const selectListfiles = ref([]);
// 选择行
const rowSelected = (selectiondata) => {
  selectListfiles.value = selectiondata.map((item) => item.fileId);
};
//进入文件夹
const gotoNewFolder = (row) => {
  rowdbselected(row);
};
const MyNavigationref = ref();
//顶部面包屑
const datalistNavigation = ref([]);
//双击行
const rowdbselected = async (row) => {
  if (row.folderType == 1) {
    const exists = datalistNavigation.value.some(
      (item) => item.fileId === row.fileId
    );
    if (!exists) {
      datalistNavigation.value.push({
        fileName: row.fileName,
        fileId: row.fileId,
      });
      currentFolder.value.fileId = row.fileId;
      loadDataList(row.fileId, 1);
    }
  }
};
//单个删除
const delfile = async (row) => {
  proxy.confirm(
    `确定删除{${row.fileName}}吗？删除的文件可通过回收站在10天内恢复`,
    async () => {
      let result = await proxy.request({
        url: api.delFile,
        params: {
          fileIds: row.fileId,
        },
      });
      if (!result) {
        return;
      }
      loadDataList(currentFolder.value.fileId);

      proxy.Mymessage.success("删除成功");
    }
  );
};
//批量删除选中文件
const deletefile = async () => {
  if (selectListfiles.value.length == 0) {
    proxy.Mymessage.error("请选择文件");
    return;
  }

  proxy.confirm("确定删除吗？删除的文件可通过回收站在10天内恢复", async () => {
    let result = await proxy.request({
      url: api.delFile,
      params: {
        fileIds: selectListfiles.value.join(","),
      },
    });
    if (!result) {
      return;
    }
    proxy.Mymessage.success("删除成功");
    loadDataList(currentFolder.value.fileId);
  });
};
//移动单个文件
const currentMovefile = ref({});
const MoveAsingleFile = async (row) => {
  currentMovefile.value = row;
  folderSelectRef.value.showFolderdialog(currentFolder.value.fileId);
};
//批量移动
const movefileBatch = async () => {
  if (selectListfiles.value.length == 0) {
    proxy.Mymessage.error("请选择文件");
    return;
  }
  currentMovefile.value = {};
  folderSelectRef.value.showFolderdialog(currentFolder.value.fileId);
};
//确定批量移动

const FolderSelectSubmitEvent = async (folderId) => {
  if (currentFolder.value.fileId == folderId) {
    proxy.Mymessage.error("不能选择当前文件夹");
    return;
  }
  let fileIds = [];
  if (currentMovefile.value.fileId) {
    //如果是单个文件
    fileIds.push(currentMovefile.value.fileId);
  } else {
    fileIds = fileIds.concat(selectListfiles.value);
  }
  let result = await proxy.request({
    url: api.changeFileFolder,
    params: {
      fileIds: fileIds.join(","),
      filePid: folderId,
    },
  });
  if (!result) {
    return;
  }
  proxy.Mymessage.success("移动成功");
  loadDataList(currentFolder.value.fileId);
};
//上传文件
const emit = defineEmits(["addfile"]);
const addfile = (fileData) => {
  emit("addfile", { file: fileData.file, filePid: currentFolder.value.fileId });
};
const currentFolder = ref({ fileId: 0 });
const cancelEdit = (index) => {
  const item = tableData.value.list[index];
  if (item.fileId) {
    item.showEidt = false;
  } else {
    tableData.value.list.splice(index, 1);
  }
  editing.value = false;
};
const SaveNameEdit = async (index) => {
  const { fileNameReal, fileId, filePid } = tableData.value.list[index];
  if (fileNameReal == "" || fileNameReal.indexOf("/") != -1) {
    proxy.Mymessage.error("文件名不能为空或包含/");
    return;
  }
  let url = api.rename;
  if (fileId == "") {
    url = api.newFolder;
  }
  let result = await proxy.request({
    url,
    params: {
      fileName: fileNameReal,
      filePid,
      fileId,
    },
  });
  if (!result) {
    return;
  }
  tableData.value.list[index] = result.data;
  editing.value = false;
};
const editing = ref(false);
const inputEditRef = ref();
const addfloder = () => {
  if (editing.value) {
    return;
  }
  tableData.value.list.forEach((item) => {
    item.showEidt = false;
  });
  editing.value = true;
  tableData.value.list.unshift({
    showEidt: true,
    fileType: 0,
    fileId: "",
    filePid: currentFolder.value.fileId,
    fileNameReal: "",
  });
  nextTick(() => {
    inputEditRef.value.focus();
  });
};
//显示操作按钮
const showOp = (row) => {
  tableData.value.list.forEach((item) => {
    item.showOp = false;
  });
  row.showOp = true;
};
const cancelOp = (row) => {
  row.showOp = false;
};
const reNamefoloderEdit = (index) => {
  if (tableData.value.list[0].fileId == "") {
    tableData.value.list.splice(0, 1);
    index--;
  }
  tableData.value.list.forEach((item) => {
    item.showEidt = false;
  });
  let currentData = tableData.value.list[index];
  currentData.showEidt = true;
  //重命名文件
  if (currentData.folderType == 0) {
    currentData.fileNameReal = currentData.fileName.substring(
      0,
      currentData.fileName.lastIndexOf(".")
    );
    currentData.fileSuffix = currentData.fileName.substring(
      currentData.fileName.lastIndexOf(".")
    );
  } else {
    currentData.fileNameReal = currentData.fileName;
    currentData.fileSuffix = "";
  }
  nextTick(() => {
    inputEditRef.value.focus();
  });
};
onMounted(() => {
  loadDataList(currentFolder.value.fileId);
});

defineExpose({
  loadDataListByCategory,
  refresh,
});
</script>

<style scoped lang="scss">
.mypagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.table-header {
  margin-bottom: 20px;
  padding: 0 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}
.file-name {
  display: flex;
  align-items: center;
  justify-content: space-between;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
}
.file-list {
  height: calc(100vh - 130px);
  display: flex;
  flex-direction: column;
  .fileName {
    text-align: center;
    display: flex;
    align-items: center;
    height: 100%;
    justify-content: flex-start;
  }
}
.fileedits {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: auto;
  flex-wrap: nowrap;
  span {
    user-select: none;
    text-align: center;
    display: flex;
    align-items: center;
    overflow-x: auto;
    margin-right: 10px;
    white-space: nowrap;
    transition: color 0.3s;
    cursor: pointer;
    &:hover {
      color: #409eff;
    }
  }
}
.edit-panle {
  display: flex;
  align-items: center;
  width: 100%;
  height: 40px;
  min-width: 250px;
}
.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;

  max-height: fit-content;
  background-color: rgb(255, 255, 255);
}
.header-actions {
  display: flex;
  justify-content: start;
  align-items: center;
  padding: 10px;

  .refresh {
    cursor: pointer;
    margin-left: 20px;
  }
  .search-panle {
    margin-left: 10px;
  }
}
.icon {
  margin-right: 5px;
}
.Mynavigation {
  margin: 5px 0 10px 20px;
}
</style>